package com.hxiaoyi.cloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 描述
 *
 * @author 黄敬意
 * @date 2022-02-05 23:52
 **/
@Component
public class MyLB implements LoadBalancer{
    /**初始原子类 为0*/
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    /**获取访问服务的次数*/
    public final int getAndIncrement(){
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current+1;
            /**自选锁*/
        }while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println("----------第几次访问服务的次数next：" + next);
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        /**算取拿个服务器作为负载均衡的服务*/
        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
